package com.xw.controller;

import antlr.collections.impl.LList;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xw.common.Constants;
import com.xw.common.Result;
import com.xw.dao.NewsDao;
import com.xw.entity.News;
import com.xw.service.NewsService;
import com.xw.util.RedisCacheUtil;
import com.xw.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 新闻管理
 * @Author: 72478
 * @Date: 2024/12/18 16:53
 * @Version: 1.0
 */

@RestController
@RequestMapping("/news")
@Api(tags = "新闻管理")
public class NewsController {

    @Resource
    private NewsDao newsDao;

    @Resource
    private NewsService newsService;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取最新的三条赛事通知
     */
    @GetMapping("/latest")
    @ApiOperation("获取最新的三条赛事通知")
    public Result<?> getLatestCompetitions() {
        String cacheKey = "latest_competitions";
        List<News> latestCompetitions = redisUtil.getCache(cacheKey, List.class);

        if (latestCompetitions == null || latestCompetitions.isEmpty()) {
            List<News> allNews = newsService.getAllNews();
            allNews.sort((a, b) -> b.getCreateTime().compareTo(a.getCreateTime()));
            latestCompetitions = allNews.stream().limit(3).collect(Collectors.toList());
            redisUtil.setCache(cacheKey, latestCompetitions);
        }

        return new Result<>(latestCompetitions, Constants.SUCCESS);
    }

    /**
     * 发布新闻
     */
    @PostMapping
    @ApiOperation("发布新新闻")
    public Result<?> publishNews(@RequestBody @Validated News news) {
        boolean success = newsService.publishNews(news);
        if (success) {
            redisUtil.deleteCache("latest_competitions");
        }
        return success ? new Result<>(Constants.SUCCESS) : new Result<>(Constants.ERROR, "发布失败");
    }

    /**
     * 获取新闻详情
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据ID获取新闻详情")
    public Result<?> getNewsById(@PathVariable("id") Integer id) {
        News news = newsDao.getNewsById(id);
        return news != null ? new Result<>(news, Constants.SUCCESS) : new Result<>(Constants.ERROR, "新闻不存在");
    }

    /**
     * 获取新闻列表或按关键字搜索

     * @return
     */
    @PostMapping("/all")
    @ApiOperation("关键字搜索新闻")
    public Result<?> getAllNews(@RequestBody Map<String, Object> params) {
        val pageNum = (int) params.getOrDefault("pageNum", 1);
        int pageSize = (int) params.getOrDefault("pageSize", 10);
        String keywords = (String) params.getOrDefault("keywords", "");

        PageHelper.startPage(pageNum, pageSize);

        List<News> newsList;
        if (keywords.isEmpty()) {
            // 获取全部新闻
            newsList = newsService.getAllNews();
        } else {
            // 按关键词搜索新闻
            newsList = newsService.searchNewsByKeywords(keywords);
        }

        PageInfo<News> pageInfo = new PageInfo<>(newsList);
        return new Result<>(pageInfo, Constants.SUCCESS);
    }

    /**
     * 更新新闻
     *
     * @return
     */
    @PutMapping("/update")
    @ApiOperation("更新新闻")
    public Result<?> updateNews(@RequestBody News news) {
        boolean success = newsService.updateNews(news);
        if (success) {
            // 清除或更新缓存
            redisUtil.deleteCache("latest_competitions"); // 删除缓存，触发下一次查询时重新加载
        }
        return success ? new Result<>(Constants.SUCCESS) : new Result<>(Constants.ERROR, "更新失败");
    }

    /**
     * 删除新闻
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @ApiOperation("删除新闻")
    public Result<?> deleteNews(@PathVariable("id") Integer id) {
        boolean success = newsService.deleteNews(id);
        if (success) {
            redisUtil.deleteCache("latest_competitions");
        }
        return success ? new Result<>(Constants.SUCCESS) : new Result<>(Constants.ERROR, "删除失败");
    }


}